package threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 描述：演示ThreadLocal的用法2：避免传递参数的麻烦
 */

public class ThreadLocalNormalUsage05 {
    public static void main(String[] args) {
        new Service1().process();
    }
}
class UserContextHolder {
    // 为每个线程分配自己的User对象
    public static ThreadLocal<User> userHolder = new ThreadLocal<>();
}
class Service1 {
    public void process () {
        // 创建User对象
        User user = new User("zhangsan");
        // 将User对象放入ThreadLocal中
        UserContextHolder.userHolder.set(user);
        // 调用Service2的process方法
        new Service2().process();
        new Service3().process();
    }
}
class Service2 {
    public void process () {
        // 从ThreadLocal中取出User对象
        User user = UserContextHolder.userHolder.get();
        System.out.println("Service2 拿到用户名" + user.name);
    }
}
class Service3 {
    public void process () {
        // 从ThreadLocal中取出User对象
        User user = UserContextHolder.userHolder.get();
        System.out.println("Service3 拿到用户名" + user.name);
        // 假设Service3是最后一个调用的方法，那么在Service3中移除ThreadLocal中的User对象
        UserContextHolder.userHolder.remove();
    }
}
class User {
    String name;
    public User(String name) {
        this.name = name;
    }
}